package com.yige.web.controller

import com.mongodb.BasicDBObject
import com.mongodb.DBObject
import com.yige.common.ArgsUtil
import com.yige.common.ExcelFileGenerator
import com.yige.common.ResultUtil
import com.yige.common.SystemConstant
import com.yige.common.ToDBObjectUtil
import com.yige.service.mongoService.MongoResourceService
import com.yige.service.mongoService.MongoRoleService
import com.yige.service.mongoService.MongoUserService
import org.apache.poi.hssf.usermodel.HSSFWorkbook
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.ui.ModelMap
import org.springframework.util.StringUtils
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.servlet.ModelAndView
import org.springframework.web.servlet.View
import org.springframework.web.servlet.view.document.AbstractExcelView

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat

/**
 * Created by sunhao on 2015/9/17 0017.
 */


@Controller
@RequestMapping("role")
class RoleController {

    @Autowired
    MongoRoleService roleService
    @Autowired
    MongoUserService userService
    @Autowired
    MongoResourceService resourceService


    /*************控制器模块************/

    /**
     * 显示角色管理页面
     * @param model
     * @return
     */
    @RequestMapping("/list.do")
    def list(Model model){
        List<DBObject> roleList = roleService.findList()
        model.addAttribute("roles",roleList)
        return "role/list"
    }

    /**
     * 多条件联合查询角色
     * @param model
     * @param name
     * @param description
     * @return
     */
    @RequestMapping("find")
    def find(Model model, String name, String description){
        def query = new BasicDBObject()
        if(!StringUtils.isEmpty(name)){
            query.append("name",~/${name}/)
        }
        if(!StringUtils.isEmpty(description)){
            query.append("description",~/${description}/)
        }
        List<DBObject> roles = roleService.findListByQuery(query)
        model.addAttribute("roles",roles)
        return "role/list"
    }

    /**
     * 添加角色
     * @param name
     * @param description
     * @return
     */
    @RequestMapping("addRole")
    @ResponseBody
    def addRole(String name,String description){
        //创建角色信息
        Map<String,Object> roleInfo = [_id:UUID.randomUUID().toString(),name:name,description:description,resource:[]]
        DBObject dbObject = ToDBObjectUtil.toDBObject(roleInfo)
        boolean flag = saveRole(dbObject)
        ResultUtil.recallAjax(flag)
    }

    /**
     * 修改角色
     * @param _id
     * @param name
     * @param description
     * @return
     */
    @RequestMapping("updateRole")
    @ResponseBody
    def updateRole(String _id, String name, String description){
        //角色信息
        Map<String,Object> roleInfo = [_id:_id,name:name,description:description,resource:[]]
        DBObject dbObject = ToDBObjectUtil.toDBObject(roleInfo),
                 role = updateRole(dbObject)
        boolean flag = false
        if(!SystemConstant.ADMINISTRATTOR_ID.equals(_id.trim())){//判断是否为超级管理员
            flag = roleService.updateOne(_id,role)
        }
        ResultUtil.recallAjaxForRole(flag,_id)
    }

    /**
     * 删除角色
     * @param _ids
     * @return
     */
    @RequestMapping("delRole")
    @ResponseBody
    def delRole(@RequestParam("_ids") List<String> _ids){
        //遍历删除角色
        boolean flag = false
        _ids.each {_id->
            if(!SystemConstant.ADMINISTRATTOR_ID.equals(_id.trim())){//判断是否为超级管理员
                flag = roleService.deleteOne(_id)
            }else {
                ResultUtil.recallAjaxForRole(flag,_id)
            }
        }
        ResultUtil.recallAjax(flag)
    }


    /**
     * 显示角色拥有资源
     * @param _id
     * @param model
     * @return
     */
    @RequestMapping("configureResource")
    def resourceConfigureRole(String roleId, Model model){
        DBObject role = roleService.findOneById(roleId),resource
        List<DBObject> allResource = resourceService.findList(),
                       resources = new ArrayList<>(), noResources
        role.resource.each {info->
            resource = resourceService.findOneById(info)
            resources.add(resource)
        }
        if(resources != null || resources.size() != 0){
            allResource.removeAll(resources)
        }
        noResources = allResource
        model.addAttribute("role",role)
        model.addAttribute("resources",resources)
        model.addAttribute("noResources",noResources)
        return "role/configure"
    }

    /**
     * 绑定角色资源
     * @param roleId
     * @param _ids
     * @return
     */
    @RequestMapping("bindResource")
    @ResponseBody
    def bindResource(@RequestParam("roleId") String roleId,
                     @RequestParam("_ids") List<String> _ids){
        boolean flag = false
        _ids.each {_id->
            flag = roleService.bindResourceForRole(roleId,_id)
        }
        ResultUtil.recallAjax(flag)
    }

    /**
     * 解除角色资源
     * @param _ids
     * @param roleId
     * @return
     */
    @RequestMapping("removeResource")
    @ResponseBody
    def removeResource(@RequestParam('_ids') List<String> _ids,
                       @RequestParam('roleId') String roleId){
        boolean flag = false
        _ids.each {_id->
            flag = roleService.removeResourceForRole(roleId,_id)
        }
        ResultUtil.recallAjax(flag)
    }


    /**
     * 导出角色表格
     * @param modelMap
     * @return
     */
    @RequestMapping("/export.do")
    def export(ModelMap modelMap){
        View view = new AbstractExcelView() {

            @Override
            protected void buildExcelDocument(Map map,
                                              HSSFWorkbook workbook, HttpServletRequest request,
                                              HttpServletResponse response) throws Exception {
                //定义Excel表参数
                String filename = new SimpleDateFormat("yyyy-MM-dd").format(new Date())+".xls";
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-disposition", "attachment;filename=" + filename) ;

                // 建立 Sheet
                List<String> fieldName = new ArrayList<>()
                fieldName.add("ID")
                fieldName.add("角色名称")
                fieldName.add("角色描述")

                List<List<Object>> fieldData = new ArrayList<>()
                List<DBObject> roleList = roleService.findList()
                roleList.each {info->
                    fieldData.add([info._id, info.name, info.description]as ArrayList)
                }
                ExcelFileGenerator excel = new ExcelFileGenerator(fieldName,fieldData)
                //开启输出流
                OutputStream ouputStream = response.getOutputStream();
                //输出Excel表
                excel.exportExcel(ouputStream)
            }
        }
        return new ModelAndView(view,modelMap)
    }


    /*************方法模块***************/

    def saveRole(DBObject roleInfo){
        ArgsUtil.checkArgs(roleInfo)
        //判断角色是否存在
        DBObject role_db = roleService.findOneById(roleInfo._id)
        if (role_db == null) {
            roleService.insertOne(roleInfo)
            return true
        }else {
            return false
        }

    }

    def updateRole(DBObject roleInfo){
        ArgsUtil.checkArgs(roleInfo)
        List<DBObject> resourceList = roleService.findAllResourceForRole(roleInfo._id),
                       resourceIds = new ArrayList<>()
        resourceList.each {resource->
            resourceIds.add(resource)
        }
        roleInfo.put("resource",resourceIds)
        return roleInfo
    }

}
